<script setup>
import { ref, onMounted } from 'vue'
import { Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { queryAllApi, addClazzApi, getClazzById, updateClazz, deleteClazz } from '@/api/clazz'
import { getAllEmps } from '@/api/emp'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单数据
const searchForm = ref({
  className: '',
  begin: '',
  end: ''
})

// 班级列表数据
const clazzList = ref([])

// 分页数据
const pageData = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 员工列表数据
const empList = ref([])

// 学科映射
const subjectMap = {
  1: 'Java',
  2: '前端',
  3: '大数据',
  4: 'Python',
  5: 'Go',
  6: '嵌入式'
}

// 对话框相关
const dialogTitle = ref('')
const dialogVisible = ref(false)
const clazzFormRef = ref()
const clazzForm = ref({
  name: '',
  room: '',
  masterId: undefined,
  beginDate: '',
  endDate: '',
  subject: undefined
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度为2-20位', trigger: 'blur' }
  ],
  beginDate: [
    { required: true, message: '请选择开课时间', trigger: 'blur' }
  ],
  endDate: [
    { required: true, message: '请选择结课时间', trigger: 'blur' }
  ]
}

// 查询方法
const handleSearch = () => {
  pageData.value.page = 1
  getClazzList()
}

// 清空方法
const handleReset = () => {
  searchForm.value.className = ''
  searchForm.value.begin = ''
  searchForm.value.end = ''
  pageData.value.page = 1
  getClazzList()
}

// 获取班级列表
const getClazzList = async () => {
  let params = {
    page: pageData.value.page,
    pageSize: pageData.value.pageSize
  }
  
  if (searchForm.value.className) {
    params.name = searchForm.value.className
  }
  if (searchForm.value.begin) {
    params.begin = searchForm.value.begin
  }
  if (searchForm.value.end) {
    params.end = searchForm.value.end
  }
  
  const result = await queryAllApi(params)
  clazzList.value = result.data.rows
  pageData.value.total = result.data.total
}

// 获取员工列表
const getEmpList = async () => {
  const result = await getAllEmps()
  empList.value = result.data
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageData.value.pageSize = val
  pageData.value.page = 1
  getClazzList()
}

const handleCurrentChange = (val) => {
  pageData.value.page = val
  getClazzList()
}

// 打开新增班级对话框
const handleAdd = () => {
  dialogTitle.value = '新增班级'
  dialogVisible.value = true
  // 重置表单
  clazzForm.value = {
    name: '',
    room: '',
    masterId: undefined,
    beginDate: '',
    endDate: '',
    subject: undefined
  }
  // 重置表单验证
  if (clazzFormRef.value) {
    clazzFormRef.value.resetFields()
  }
}

// 编辑班级
const handleEdit = async (row) => {
  dialogTitle.value = '编辑班级'
  dialogVisible.value = true
  // 回显数据
  const result = await getClazzById(row.id)
  clazzForm.value = result.data
}

// 删除班级
const handleDelete = (row) => {
  ElMessageBox.confirm('此操作将永久删除该班级, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除班级
    const result = await deleteClazz(row.id)
    if (result.code) {
      ElMessage.success('删除成功')
      getClazzList()
    } else {
      ElMessage.error(result.msg)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 保存班级
const saveClazz = async () => {
  // 表单验证
  await clazzFormRef.value.validate()
  let result = null
  // 判断是新增还是编辑
  if (clazzForm.value.id) {
    result = await updateClazz(clazzForm.value)
  } else {
    result = await addClazzApi(clazzForm.value)
  }
  
  if (result.code) {
    // 关闭对话框
    dialogVisible.value = false
    // 提示成功
    ElMessage.success('操作成功')
    // 重新加载列表
    getClazzList()
  } else {
    // 提示失败
    ElMessage.error(result.msg)
  }
}

// 页面加载时获取数据
onMounted(() => {
  getClazzList()
  getEmpList()
})


</script>

<template>
  <div class="class-management">
    <h1>班级管理</h1>
    <br>
    <br>
    <!-- 搜索区域 -->
    <el-form :model="searchForm"  inline style="text-align: left;">
      <el-form-item label="班级名称">
        <el-input 
          v-model="searchForm.className" 
          placeholder="请输入班级名称" 
          clearable
        />
      </el-form-item>
      
      <el-form-item label="开课时间">
        <el-date-picker
          v-model="searchForm.begin"
          type="date"
          placeholder="请选择开课时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      
      <el-form-item label="结课时间">
        <el-date-picker
          v-model="searchForm.end"
          type="date"
          placeholder="请选择结课时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button 
          type="primary" 
          :icon="Search" 
          @click="handleSearch"
        >
          查询
        </el-button>
        <el-button 
          :icon="Refresh" 
          @click="handleReset"
        >
          清空
        </el-button>
      </el-form-item>
    </el-form>
    
    <!-- 新增按钮区域 -->
    <div style="text-align: left; margin: 20px 0;">
      <el-button 
        type="primary" 
        @click="handleAdd"
      >
        + 新增班级
      </el-button>
    </div>
    
    <!-- 班级列表 -->
    <el-table :data="clazzList" border stripe style="width: 100%; margin-top: 20px;" :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="name" label="班级名称" />
      <el-table-column prop="room" label="班级教室" width="110" />
      <el-table-column prop="masterName" label="班主任" width="110"/>
      <el-table-column prop="beginDate" label="开课时间"  />
      <el-table-column prop="endDate" label="结课时间"  />
      <el-table-column prop="status" label="状态" width="110">
        <template #default="scope">
          <el-tag :type="scope.row.status === '在读' ? 'success' : scope.row.status === '已结课' ? 'danger' : 'info'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最后修改时间" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button 
            type="primary" 
            link 
            :icon="Edit" 
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            type="danger" 
            link 
            :icon="Delete" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pageData.page"
      v-model:page-size="pageData.pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :total="pageData.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: flex-start;"
    />
  </div>
  
  <!-- 新增/编辑班级对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
    <el-form 
      ref="clazzFormRef" 
      :model="clazzForm" 
      :rules="rules" 
      label-width="100px"
    >
      <el-form-item label="班级名称" prop="name">
        <el-input 
          v-model="clazzForm.name" 
          placeholder="请输入班级名称，长度为2-20位" 
        />
      </el-form-item>
      
      <el-form-item label="班级教室" prop="room">
        <el-input 
          v-model="clazzForm.room" 
          placeholder="请输入班级教室" 
        />
      </el-form-item>
      
      <el-form-item label="班主任" prop="masterId">
        <el-select 
          v-model="clazzForm.masterId" 
          placeholder="请选择班主任" 
          style="width: 100%"
        >
          <el-option
            v-for="emp in empList"
            :key="emp.id"
            :label="emp.name"
            :value="emp.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="开课时间" prop="beginDate">
        <el-date-picker
          v-model="clazzForm.beginDate"
          type="date"
          placeholder="请选择开课时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="结课时间" prop="endDate">
        <el-date-picker
          v-model="clazzForm.endDate"
          type="date"
          placeholder="请选择结课时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="学科" prop="subject">
        <el-select 
          v-model="clazzForm.subject" 
          placeholder="请选择学科"
          style="width: 100%"
        >
          <el-option
            v-for="(label, key) in subjectMap"
            :key="key"
            :label="label"
            :value="Number(key)"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveClazz">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.class-management {
  padding: 20px;
}
</style>